package ui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.HashMap;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XsltTransformer;

import org.jdesktop.jdic.browser.WebBrowser;

import automatica.autoprove.CallBacks;

import com.maplesoft.externalcall.MapleException;
import com.maplesoft.openmaple.Engine;

import prefuse.data.Table;


import ui.frame.GTextbook;
import ui.frame.GTFrame.LangMenu;
import ui.frame.dialog.DialogConstants;
import ui.frame.dialog.QueryPanel;
import ui.frame.dialog.panel.FigurePage;
import ui.frame.dialog.panel.FigurePanel;
import ui.frame.dialog.panel.RelationPage;
import ui.frame.dialog.panel.RelationPanel;
import ui.frame.dialog.panel.TextTabbedPage;
import ui.view.NodeInfo;
import ui.view.GTView;
import ui.view.IndexTreeNode;
import ui.view.IndexTreeView;
import ui.view.LangWarningPane;
import ui.view.ShowFrame;

import static constants.GTextbookConstants.*;

public class Utility{
 
	public static String toPattern(String str){
		StringBuffer result = new StringBuffer();
		if(str!=null){
		char[] chars = new char[str.length()];
		str.getChars(0, str.length(), chars, 0);
		for(int i =0; i<chars.length;i++){
			if(chars[i]=='('|chars[i]==')'|chars[i]=='['|chars[i]==']'|chars[i]=='{'|chars[i]=='}'){
				result.append('\\');	
			}
			result.append(chars[i]);
		}
		}
		return result.toString();
	}
	
	//old version of suqote2dquote
	/*
	public static String squote2dquote(String str){
		StringBuffer result = new StringBuffer();
		if(str!=null){
		char[] chars = new char[str.length()];
		str.getChars(0, str.length(), chars, 0);
		boolean left = false;
		boolean right = false;
		for(int i =0; i<chars.length;i++){
			if(chars[i]=='<'){
				left = true;
				right = false;
			}
			if(chars[i]=='>'){
				right = true;
				left = false;
			}
			if(left==right){
				if(chars[i]== '\''){
					result.append('\'');
					result.append('\'');
				}else
					result.append(chars[i]);
			}else{
				if(chars[i]== '\''){
					result.append('\"');
				}else
					result.append(chars[i]);	
			}
			
		}
		}
		return result.toString();
	}
	*/
	public static String squote2dquote(String str){
		StringBuffer result = new StringBuffer();
		if(str!=null){
			char[] chars = new char[str.length()];
			str.getChars(0, str.length(), chars, 0);
			boolean left = false;
			boolean right = false;
			for(int i =0; i<chars.length;i++){
				if(chars[i]== '\''){
					if(i+1<chars.length&&chars[i+1]!= '\''){
						result.append('\'');
						result.append('\'');
					}
				}else
					result.append(chars[i]);
			}
		}
		return result.toString();
	}

	
	public static Vector<String> getItemsBySemicolon(String str){
		Vector<String> result = new Vector<String>(1,1);
		String reg = ";|；";                        
	    Pattern pattern = Pattern.compile(reg);
	    Matcher m = pattern.matcher(str);
	    int start = 0;
	    int end = str.length();
	    while(m.find()){
	    	result.add(str.substring(start,m.start()));
	    	start=m.end();
	    }
	    if(start!=end){
	    	result.add(str.substring(start,end));
	    }
		return result;
	}
	
	public static Vector<String> getItemsBySeparator(String str, String s){
		Vector<String> result = new Vector<String>(1,1);
		String reg = ";|；|\\"+s;                        
	    Pattern pattern = Pattern.compile(reg);
	    Matcher m = pattern.matcher(str);
	    int start = 0;
	    int end = str.length();
	    while(m.find()){
	    	result.add(str.substring(start,m.start()));
	    	start=m.end();
	    }
	    if(start!=end){
	    	result.add(str.substring(start,end));
	    }
		return result;
	}

//É¾³ýÐÎÊ½Óï¾äÖÐµÄÒªÉ¾³ýµÄÖ¸¶¨×Ö·û£¬\\s£¬;µÈ
  public static String deleteSpace(String test){
      StringBuffer result = new StringBuffer();
      String reg = "\\s";                        //Ö¸¶¨ÒªÉ¾³ýµÄ×Ö·û
      Pattern pattern = Pattern.compile(reg);
      Matcher m = pattern.matcher(test);      
      Vector<Integer> spaceIndex = new Vector<Integer>(10,10);
      int start = 0;
      int end = 0;
      while( m.find() ){
      spaceIndex.add(m.start());                   //±ê¼ÇÒªÉ¾³ýµÄ×Ö·û
     }
     if(spaceIndex.isEmpty())
      return test;
     else{
         for(int i = 0; i < spaceIndex.size();i++){          
            end = spaceIndex.get(i);
            if(start == end){
               start = end+1;
            if(start > test.length()-1)
              break;
            if(i == spaceIndex.size()-1)
               end = test.length();
            else{                 
               end = spaceIndex.get(i+1);
               continue;
            }
            }  
            result.append(test.substring(start,end));
            start = end +1;
            if(start > test.length())
               break;        
         }
         if(start <= test.length()-1){      
         end = test.length();
         result.append(test.substring(start,end));
         }
     return result.toString();
        }
    }
     
      

   
   //Éú³É×Ó¾äÄ£Ïî,µÚÒ»Î»ÎªÎ½´Ê£¬ÒÔºó¸÷Î»ÎªÏî
   public static Vector<String> generateTermSet(String test){
      int[][] t = matchPairs(test);
    //  System.out.println("The pairs of parentheses are: ");
      //for(int i = 0; i < t.length; i++){
     //    System.out.println("start " + t[i][0] + " end "+ t[i][1]);
      //}
      Vector<String> term = new Vector<String>(5,5);
      term.add(test.substring(0,t[0][0]));
      int begin = t[0][0]+1;
      int over = 0;
      while(begin < test.length()){
         for(int point = begin;point < test.length();point++){
            if(test.charAt(point)=='('||test.charAt(point)=='（'){
               for(int y = 0;y < t.length;y++){
                  if(t[y][0] == point)
                    { 
                    point = t[y][1]+1;
                  //  System.out.println("The mark of extracted term: "+ t[y][1]);
                    break;
                    }
                                          
               }
            }
            if(test.charAt(point)==','||test.charAt(point)=='；'||test.charAt(point)==')'||test.charAt(point)=='）'){
               over = point;
               break;
            }
            
         }  
            
         //È·¶¨ÖÕµã
         if(begin!=over){
         term.add(test.substring(begin,over));
         System.out.println("Start: " + begin + "||Over: " + over);
         }									//ÌáÈ¡Ïî
         begin = over+1;                                //ÖØÐÂÌáÈ¡ 


        
       
         
      }
    //  System.out.println("The size of termSet: " + term.size());
     // System.out.println("The term in termSet are:\n");
     // for(int index = 0; index < term.size();index++){        
      //  System.out.println(index + " " + term.get(index));
      //}
      return term;
   }
   
   //À¨ºÅÅä¶Ô
  public static int[][] matchPairs(String test){
      
      Vector<Integer> textBone = new Vector<Integer>(10,10);
      String regEx = "\\(|\\)|\\（|\\）";
      Pattern pattern = Pattern.compile(regEx);
      Matcher m = pattern.matcher(test);
      
     while( m.find() ){
   //   System.out.println("Parentheses found at Start: "+m.start());
      textBone.add(m.start());
     }
     
     int[][] pairs = new int[textBone.size()/2][2];
     int count = 0;
     int start = 0;
     int end = 0;
     int n = 0;
    
    for(int j = 0; j < textBone.size(); j++){
      start = textBone.get(j);
      if (textBone.get(j)==0)
         continue;
      else{      
         int t = j;
         do {
            if (test.charAt(textBone.get(t))=='('||test.charAt(textBone.get(t))=='（'){
               count++;
               t++;
            }
            if (test.charAt(textBone.get(t))==')'||test.charAt(textBone.get(t))=='）'){
               count--;
               t++;
            }   
         }while(count!=0);
         end = textBone.get(t-1);
         textBone.set(t-1,0);
         t++;
         pairs[n][0] = start;  //½«Åä¶ÔµÄ½á¹ûÐ´Èë¶þÎ»Êý×é
         pairs[n][1] = end;
         n++;
      }
   }
  return pairs;
}
  
  public static Vector<String> generateTermSetWithSpace(String test, char left, char right){
	 //test = deleteSpace(test);
	  test = test.trim();
     int[][] t = matchPairs(test,left,right);
   //  System.out.println("The pairs of parentheses are: ");
     //for(int i = 0; i < t.length; i++){
    //    System.out.println("start " + t[i][0] + " end "+ t[i][1]);
     //}
     Vector<String> term = new Vector<String>(5,5);
     term.add(test.substring(0,t[0][0]));
     int begin = t[0][0]+1;
     int over = 0;
     while(begin < test.length()){
        for(int point = begin;point < test.length();point++){
           if(test.charAt(point)==left||test.charAt(point)=='('){
              for(int y = 0;y < t.length;y++){
                 if(t[y][0] == point)
                   { 
                   point = t[y][1]+1;
                 //  System.out.println("The mark of extracted term: "+ t[y][1]);
                   break;
                   }
                                         
              }
           }
           if(test.charAt(point)==','||test.charAt(point)==right||test.indexOf(point)=='；'||test.charAt(point)==')'){
              over = point;
              break;
           }
           
        }  				//È·¶¨ÖÕµã
        
        if(begin!=over || begin > over){
       	 term.add(test.substring(begin,over));       //ÌáÈ¡Ïî
        }
        begin = over+1;                                //ÖØÐÂÌáÈ¡ 
        
     }
   //  System.out.println("The size of termSet: " + term.size());
    // System.out.println("The term in termSet are:\n");
    // for(int index = 0; index < term.size();index++){        
     //  System.out.println(index + " " + term.get(index));
     //}
     return term;
  }
  
  
 
 public static int[][] matchPairs(String test, char left, char right){
     Vector<Integer> textBone = new Vector<Integer>(10,10);
     String regEx = "\\" +left+"|"+ "\\"+right+"|\\(|\\)";
     Pattern pattern = Pattern.compile(regEx);
     Matcher m = pattern.matcher(test);
     
    while( m.find() ){
  //   System.out.println("Parentheses found at Start: "+m.start());
     textBone.add(m.start());
    }
    
    int[][] pairs = new int[textBone.size()/2][2];
    int count = 0;
    int start = 0;
    int end = 0;
    int n = 0;
   
   for(int j = 0; j < textBone.size(); j++){
     start = textBone.get(j);
     if (textBone.get(j)==0)
        continue;
     else{      
        int t = j;
        do {
           if (test.charAt(textBone.get(t))==left||test.charAt(textBone.get(t))=='('){
              count++;
              t++;
           }
           if (test.charAt(textBone.get(t))==right||test.charAt(textBone.get(t))==')'){
              count--;
              t++;
           }   
        }while(count!=0);
        end = textBone.get(t-1);
        textBone.set(t-1,0);
        t++;
        pairs[n][0] = start;  //½«Åä¶ÔµÄ½á¹ûÐ´Èë¶þÎ»Êý×é
        pairs[n][1] = end;
        n++;
     }
  }
 return pairs;
}
  
   //¼ì²âÓÐÎÞÎ½´Ê
   public static boolean havePredicate(String test){
      String reg = "\\(|\\（";
      Pattern pattern = Pattern.compile(reg);
      Matcher m = pattern.matcher(test);
      if(m.find())
      return true;
      else
      return false;
   }
   
   
   
   
      
      
     public static Vector<String> generateOM(String name, String reference, String...args){
      
      Vector<String> patOM = new Vector<String>(5,5);
      
      patOM.add("<OMA><OMS cd=\""+ reference + "\" name=\"" + name + "\"/>\n");
      
      for(int i=0; i< args.length; i++){
      	patOM.add(args[i]);
      }
      
      patOM.add("</OMA>\n");
      
      return patOM;
      
      }
      
    
      
      
      public static Vector<String> extractPoint(String str){
      	Vector<String> term = new Vector<String>(5,5);
      	Vector<String> buf = new Vector<String>(5,5);
      	term = generateTermSet(str);
      	if(!term.get(0).equals("integer"))
      		
      		for(int i = 1; i < term.size(); i++){
      		
      		   if(havePredicate(term.get(i)))
      		      buf.addAll(extractPoint(term.get(i)));
      		   else
      		      buf.add(term.get(i));
      	     }
      	
      	return buf;
      }
      
      public static Vector<String> reduce(Vector<String> pointList){
      	Vector<String> buf = new Vector<String>(5,5);
      	if(pointList.size()==1)  return pointList;
      	else{     	
      	  for(int i = 0; i < pointList.size()-1; i++){
      		for(int j = i + 1; j < pointList.size(); j++){
      			if(pointList.get(i).equals(pointList.get(j))){
      				pointList.remove(j);
      				reduce(pointList);
      			}
      		 }
      	  }
      	}
      	
      	return pointList;
      }
      
      
  public static String putIndent(int blank){
      StringBuffer buf = new StringBuffer(10);
      for(int i = 0; i < blank; i++){
            	buf.append(Indent);
            }
      return buf.toString();
      }
  
  //connect to SQL server 2000
  public static Connection createConnection(String dataBaseName, String user, String password){
	  Connection con = null;
	  String url = constants.GTextbookConstants.DriverURL+dataBaseName;
	  
	  try{    
          
		  Class.forName(constants.GTextbookConstants.DriverName);

          con = DriverManager.getConnection( url, user, password );

      }
      catch(Exception err){
    	  LangWarningPane.showMessageDialog(null,"Cannot connect to the DATABASE!", "连接数据库错误!", "Connection Error", "连接错误", JOptionPane.ERROR_MESSAGE, language.getNum());			
          err.printStackTrace(System.out);
      }
      
      return con;

  }
  
  
  /*
  public static Connection createConnection(String dataBaseName, String user, String password){
	  Connection con = null;
	  String url = "jdbc:mysql://localhost/"+dataBaseName;
      try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 
          Class.forName("com.mysql.jdbc.Driver");
          //System.out.println("driver successful!");

          con = DriverManager.getConnection( url,user, password );
         
          if(!con.isClosed()){
        	  //System.out.println("Succeed connecting to the database!");
          }
          
      }
      catch(Exception err){
          err.printStackTrace(System.out);
      }
      
      return con;

  }
  */
  
  //decide whether A exist in list B
  public static boolean existIn(String A, Vector<String> B){
	  boolean result = false;
	  for(int i = 0; i < B.size(); i++){
		  if(A.equals(B.elementAt(i))){
			  result = true;
			  break;
		  }
	  }
	  
	  
	  return result;
  }
  
  
  /*
   * transform the file of sourcePath into a file of resultPath using xsl of xslPath
   */
  public static void transformation(String sourcePath, String xslPath, String resultPath, String type)throws SaxonApiException{
		
		Processor proc = new Processor(false);
      XsltCompiler comp = proc.newXsltCompiler();
      XsltExecutable exp = comp.compile(new StreamSource(new File(xslPath)));
      XdmNode source = proc.newDocumentBuilder().build(new StreamSource(new File(sourcePath)));
      Serializer out = new Serializer();
      out.setOutputProperty(Serializer.Property.METHOD, type);
      out.setOutputProperty(Serializer.Property.INDENT, "no");
      out.setOutputFile(new File(resultPath));
      XsltTransformer trans = exp.load();
      trans.setInitialContextNode(source);
      trans.setDestination(out);
      trans.transform();
	}
	

	  
	  public static void saveFile(JFrame window, String content, File outFile) {
		     
		    FileOutputStream outputFile = null;     // Place to store the stream reference
		    try {
		    	
		    	if(content != null){
		    		outputFile = new FileOutputStream(outFile, false);
		                                
		    		System.out.println("File stream created successfully.");
		    		
		    		
		    		
		    		// important
		    		Writer w = new OutputStreamWriter(outputFile, "UTF-8"); 
      
		    		w.write(content);
		    		w.close();
		    		System.out.println("File contents written to file.");
		    	}else{
		    		System.out.println("The content is null");
		    	}
		      
		    } catch (FileNotFoundException e) {
		      e.printStackTrace(System.err);
		    } catch(IOException e) {
		      System.err.println(e);
		      JOptionPane.showMessageDialog(window,
		                                    "Error writing a file.",
		                                    "File Output Error",
		                                    JOptionPane.ERROR_MESSAGE);
		      return;                                    // Serious error - return
		    }
		           
	}
	  
	  public static String readFile(String path) throws IOException{
          InputStream  is  =  new  FileInputStream(path);
          StringBuffer  buffer  =  new  StringBuffer();
          readToBuffer(buffer,  is);
          //System.out.println(buffer);          //  ½«¶Áµ½  buffer  ÖÐµÄÄÚÈÝÐ´³öÀ´
          is.close();
          return buffer.toString();
	  }
	  
      public  static void  readToBuffer(StringBuffer  buffer,  InputStream  is)throws  IOException  {
    	  String  line;                //  ÓÃÀ´±£´æÃ¿ÐÐ¶ÁÈ¡µÄÄÚÈÝ
    	  BufferedReader  reader  =  new  BufferedReader(new  InputStreamReader(is));
    	  line  =  reader.readLine();              //  ¶ÁÈ¡µÚÒ»ÐÐ
    	  while  (line  !=  null)  {                    //  Èç¹û  line  Îª¿ÕËµÃ÷¶ÁÍêÁË
              buffer.append(line);                //  ½«¶Áµ½µÄÄÚÈÝÌí¼Óµ½  buffer  ÖÐ
              buffer.append("\n");                //  Ìí¼Ó»»ÐÐ·û
              line  =  reader.readLine();      //  ¶ÁÈ¡ÏÂÒ»ÐÐ
    	  }
      }
      
      /**
       *  2.  ÑÝÊ¾½«  StringBuffer  ÖÐµÄÄÚÈÝ¶Á³öµ½Á÷ÖÐ
       */
     public  void  writeFromBuffer(StringBuffer  buffer,  OutputStream  os)  {
             //  ÓÃ  PrintStream  ¿ÉÒÔ·½±ãµÄ°ÑÄÚÈÝÊä³öµ½Êä³öÁ÷ÖÐ
             //  Æä¶ÔÏóµÄÓÃ·¨ºÍ  System.out  Ò»Ñù
             //  £¨System.out  ±¾Éí¾ÍÊÇ  PrintStream  ¶ÔÏó£©
             PrintStream  ps  =  new  PrintStream(os);      
             ps.print(buffer.toString());
     }
     /**
       *  3*.  ´ÓÊäÈëÁ÷ÖÐ¿½±´ÄÚÈÝµ½ÊäÈëÁ÷ÖÐ
       *  @throws  IOException
       */
     public  void  copyStream(InputStream  is,  OutputStream  os)  throws  IOException  {
             //  Õâ¸ö¶Á¹ý¹ý³Ì¿ÉÒÔ²ÎÔÄ  readToBuffer  ÖÐµÄ×¢ÊÍ
             String  line;
             BufferedReader  reader  =  new  BufferedReader(new  InputStreamReader(is));
             PrintWriter  writer  =  new  PrintWriter(new  OutputStreamWriter(os));
             line  =  reader.readLine();
             while  (line  !=  null)  {
                     writer.println(line);
                     line  =  reader.readLine();
             }
             writer.flush();          //  ×îºóÈ·¶¨Òª°ÑÊä³öÁ÷ÖÐµÄ¶«Î÷¶¼Ð´³öÈ¥ÁË
                                                     //  ÕâÀï²»¹Ø±Õ  writer  ÊÇÒòÎª  os  ÊÇ´ÓÍâÃæ´«½øÀ´µÄ
                                                     //  ¼ÈÈ»²»ÊÇ´ÓÕâÀï´ò¿ªµÄ£¬Ò²¾Í²»´ÓÕâÀï¹Ø±Õ
                                                     //  Èç¹û¹Ø±ÕµÄ  writer£¬·â×°ÔÚÀïÃæµÄ  os  Ò²¾Í±»¹ØÁË
     }
	
	  public static void openGeogebra(int language){
 	 		ShowFrame frame = new ShowFrame("GeoGebra", "GeoGebra", language);
   	 		frame.setVisible(true);
		    Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
   	 		frame.setBounds(0,size.height/3,2*size.width/3,2*size.height/3);
		    //render the construct ggb
			String source = GEOGEBRA_DIRECTORY + "/dynamicSource.xml";
			String xsl = XSL_EGT_DIRECTORY + "style.xsl";
			String output = GEOGEBRA_DIRECTORY + "/dynamicOutput.xml";
			frame.show("file:///"+output);
	  }
	  
	  public static void openFormulaEditor(int language){
 	 		//ShowFrame frame = new ShowFrame("http://192.168.6.205:8080/mathdoxplayer/GTextbook/formulaeditor/blank.html", "MathDox Formula Editor", "MathDox公式编辑器", language);
 	 		ShowFrame frame = new ShowFrame("file:///"+RESOURCE_DIRECTORY+"/formulaeditor.html", "MathDox Formula Editor", "MathDox公式编辑器", language);
 	 		frame.setVisible(true);
  	        Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
   	 		frame.setBounds(0, 0, size.width/2,size.height/2);
	  }
	  

	    /**remove the information with knowledgeID*/
	    public static boolean removeFromKB(String knowledgeID, String role) {

	            	boolean result = true;
          				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
          	
	   	           	   knowledgeID = Utility.squote2dquote(knowledgeID);
	   	        	   
	   	        	   
		 	            //ÓÉÓÚrole²»Í¬µÄ²»Í¬²Ù×÷
		 	            if(role.equals("Definition")){

		 	        		
		 	       		 try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

		 	       	          Statement st = con.createStatement();
		 	       	          //System.out.println( "´´½¨Statement³É¹¦!" );
		 	       	          
		 	       	          st.executeUpdate("delete from knowledgeName where role='Definition' and knowledgeName=(select knowledgeName from concept where conceptID='"+knowledgeID+"')");
			 	    			System.out.println( "É¾³ýnameÊý¾Ý±í³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			
			 	    			//½«objectID´ÓKOstructureÖÐÉ¾³ý
			 	       	        st.executeUpdate("delete from KOstructure where precursor in (select objectID from definitionObject where conceptID='"+knowledgeID+"')");
			 	    			System.out.println( "É¾³ýprecursor³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			
			 	    			st.executeUpdate("delete from KOstructure where subsequence in (select objectID from definitionObject where conceptID='"+knowledgeID+"')");
			 	    			System.out.println( "É¾³ýsubsequence³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			
			 	    				 	    			
			 	    			
		 	       	          //ÏÖ½«objectID´ÓobjectTypeÖÐÉ¾³ý
			 	       	        st.executeUpdate("delete from objectType where objectID in (select objectID from definitionObject where conceptID='"+knowledgeID+"')");
			 	    			System.out.println( "É¾³ýobjectTypeÊý¾Ý±í³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			

			 	    			
			 	    			

			 	    			//×îºóÉ¾³ýconcept
			 	    			st.executeUpdate("delete from concept where conceptID='"+knowledgeID+"'");
			 	    			System.out.println( "É¾³ýknowledgeÊý¾Ý±í³É¹¦!" );
			 	    			System.out.println( "----------------!" );
		 	       	          
			 	    			

			 	    			
			 	    			st.close();
		 	       	          con.close();	 
		 	       	      }
		 	       	      catch(Exception err){
		 	       	          err.printStackTrace(System.out);
		 	       	          result = false;
		 	       	      }
		 	            	
		 	            }else if(role.equals("Axiom")||role.equals("Lemma")||role.equals("Theorem")||role.equals("Corollary")||role.equals("Conjecture")||role.equals("Problem")||role.equals("Proof")||role.equals("Exercise")||role.equals("Example")||role.equals("Algorithm")||role.equals("Introduction")||role.equals("Remark")||role.equals("Solution")){
		 	            	
			 	       		 try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			 	       	          Statement st = con.createStatement();
			 	       	          //System.out.println( "´´½¨Statement³É¹¦!" );
			 	       	          
			 	       	          //É¾³ýname
			 	       	          if(role.equals("Axiom")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Axiom' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			 
			 	       	          }else if(role.equals("Lemma")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Lemma' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Theorem")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Theorem' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			 
			 	       	          }else if(role.equals("Corollary")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Corollary' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			 
			 	       	          }else if(role.equals("Conjecture")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Conjecture' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Problem")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Problem' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Exercise")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Exercise' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Example")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Example' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Proof")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Proof' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Algorithm")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Algorithm' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Introduction")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Introduction' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Remark")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Remark' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }else if(role.equals("Solution")){
			 	       	        	st.executeUpdate("delete from knowledgeName where role='Solution' and knowledgeName=(select knowledgeName from knowledge where knowledgeID='"+knowledgeID+"')");
				 	    			
			 	       	          }
			 	       	          System.out.println( "É¾³ýnameÊý¾Ý±í³É¹¦!" );
				 	    			System.out.println( "----------------!" );
				 	    			
				 	    			
				 	    		//½«knowledgeID´ÓKOstructureÖÐÉ¾³ý
				 	       	    st.executeUpdate("delete from KOstructure where precursor in (select objectID from knowledgeObject where knowledgeID='"+knowledgeID+"')");
				 	       	    System.out.println( "É¾³ýprecursor³É¹¦!" );
				 	    		System.out.println( "----------------!" );
				 	    			
				 	    		st.executeUpdate("delete from KOstructure where subsequence in (select objectID from knowledgeObject where knowledgeID='"+knowledgeID+"')");
				 	    		System.out.println( "É¾³ýsubsequence³É¹¦!" );
				 	    		System.out.println( "----------------!" );
			 	       	          
			 	       	          //ÏÖ½«objectID´ÓobjectTypeÖÐÉ¾³ý
			 	       	        st.executeUpdate("delete from objectType where objectID in (select objectID from knowledgeObject where knowledgeID='"+knowledgeID+"')");
			 	    			System.out.println( "É¾³ýobjectTypeÊý¾Ý±í³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			


			 	    			//×îºóÉ¾³ýknowledge
			 	    			st.executeUpdate("delete from knowledge where knowledgeID='"+knowledgeID+"'");
			 	    			System.out.println( "É¾³ýknowledgeÊý¾Ý±í³É¹¦!" );
			 	    			System.out.println( "----------------!" );
			 	    			

			 	    			
			 	       	          st.close();
			 	       	          con.close();	 
			 	       	      }
			 	       	      catch(Exception err){
			 	       	          err.printStackTrace(System.out);
			 	       	          result = false;
			 	       	      }
		 	            	
		 	            }else{
		 	            	//for category
		 	            	//the objectID of category is also its knoweledgeID
		 	            	try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

		 		       	          Statement st = con.createStatement();
		 		       	          //System.out.println( "´´½¨Statement³É¹¦!" );
		 		       	          
		 		       	      	  //import data into database
		 		       	          
		 		       	          System.out.println(knowledgeID);
		 		       	        
		 		       	        st.executeUpdate("delete from objectType where objectID in (select objectID from categoryObject where categoryID='"+knowledgeID+"')");

		 		    			System.out.println( "É¾³ýcategoryObjectÊý¾Ý±í³É¹¦!" );
		 		    			System.out.println( "----------------!" );

		 		    			
		 		    			
		 		       	          st.close();
		 		       	          con.close();	 
		 		       	      }
		 		       	      catch(Exception err){
		 		       	          err.printStackTrace(System.out);
		 		       	          result = false;
		 		       	      }
		 	            }
		   	     

	         
	   	        // Either there was no selection, or the root was selected.
	        Toolkit.getDefaultToolkit().beep();
	        return result;

	    }
	    
	    /**
	     * Fetch data items from the database
	     * 
	     * 
	     */
	    
	    /** fetch single information from the database*/
	    public static String getObjectID(String knowledgeID, String version, int type){
			knowledgeID = Utility.squote2dquote(knowledgeID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getObjectID = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(type == Definition){
				getObjectID = "select objectID from objectType where version='" + version + "' and objectID in (select objectID from definitionObject where conceptID='" + knowledgeID +"')";
			}else if(type == Introduction || type == Remark){
				//Ö¤Ã÷£¬½éÉÜ£¬×¢ÊÍµÄobjectIDÓÉÓïÑÔ¾ö¶¨
				getObjectID = "select objectID from objectType where version='" + language.getString() + "' and objectID in (select objectID from knowledgeObject where knowledgeID='" + knowledgeID +"')";
			}else
			if(Utility.checkOntology("roleOntology", type , "precursorNum", knowledgeObject, "subsequenceNum", "is")){
				//ÆäËûµÄÓÉversion¾ö¶¨
				getObjectID = "select objectID from objectType where version='" + version + "' and objectID in (select objectID from knowledgeObject where knowledgeID='" + knowledgeID +"')";
			}else{
				//for category
				getObjectID = "select objectID from categoryObject where language='" + version +"' and categoryID='" + knowledgeID +"'";
			}
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getObjectID );
				System.out.println( "getObjectID³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("objectID");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
				
		}
	    
	    public static String getAllName(String knowledgeID,int type) {
			// TODO Auto-generated method stub
			knowledgeID = Utility.squote2dquote(knowledgeID);
			StringBuffer result = new StringBuffer();
			String getKnowledgeName = null;
			String knowledgeName = null;
			
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			if(Utility.checkOntology("roleOntology", type , "precursorNum", knowledgeObject, "subsequenceNum", "is")){
				
				if(type == Definition){
					getKnowledgeName = "select knowledgeName from concept where conceptID='" + knowledgeID +"'";
				}else{
					getKnowledgeName = "select knowledgeName from knowledge where knowledgeID='" + knowledgeID +"'";
				}

				Statement st;
				try{
					st = con.createStatement();
					resultSet = st.executeQuery( getKnowledgeName );
					System.out.println( "getKnowledgeName³É¹¦!" );
					System.out.println( "----------------!" );
					while(resultSet.next())
					{
						knowledgeName = resultSet.getString("knowledgeName");
					}
					
					String getName = "select distinct name from knowledgeName where knowledgeName='" + Utility.squote2dquote(knowledgeName) + "'";

					resultSet = st.executeQuery( getName );
					System.out.println( "getName³É¹¦!" );
					System.out.println( "----------------!" );
					while(resultSet.next())
					{
						String n = resultSet.getString("name");
                		if(n!=null&&n!=""){
                			Statement st2 = con.createStatement();
                			ResultSet languagers = st2.executeQuery("select distinct language from knowledgeName where name='" + Utility.squote2dquote(n)+"'");
                			while(languagers.next()){
                				result.append(n+"("+languagers.getString("language")+");");
                			}
                			st2.close();
                			languagers.close();
                		}
					}
					
					
					resultSet.close();
					st.close();
					con.close();
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				 String getName = "select name,language from categoryObject where categoryID='" + knowledgeID +"'";
					Statement st;
					try{
						st = con.createStatement();
						resultSet = st.executeQuery( getName );
						while(resultSet.next())
						{
							result.append(resultSet.getString("name")+"("+resultSet.getString("language")+");");;
						}
						
						resultSet.close();
						st.close();
						con.close();
					}catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

			}
			return result.toString();
		}
	    
	    public static String getAllCategoryRole(String categoryID){
	    	categoryID = Utility.squote2dquote(categoryID);
			StringBuffer result = new StringBuffer();

			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getRole = "select role,language from categoryObject where categoryID='" + categoryID +"'";
			Statement st;
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getRole );
				while(resultSet.next())
				{
					result.append(resultSet.getString("role")+"("+resultSet.getString("language")+");");;
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result.toString();

	    }
	    public static String getCategoryRole(String categoryID, int language){
	    	categoryID = Utility.squote2dquote(categoryID);
			String result = null;
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getRole = "select role from categoryObject where categoryID='" + categoryID +"' and language='" + lang +"'";
			Statement st;
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getRole );
				while(resultSet.next())
				{
					result=resultSet.getString("role");
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result;

	    }
	    
	    public static String getCategoryNote(String categoryID, int language){
	    	categoryID = Utility.squote2dquote(categoryID);
			StringBuffer result = new StringBuffer();
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getRole = "select note from categoryObject where categoryID='" + categoryID +"' and language='"+lang+"'";
			Statement st;
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getRole );
				while(resultSet.next())
				{
					result.append(resultSet.getString("note"));;
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result.toString();

	    }
	    
	    public static String getAllCategoryTitle(String categoryID){
	    	categoryID = Utility.squote2dquote(categoryID);
			StringBuffer result = new StringBuffer();

			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getRole = "select title,language from categoryObject where categoryID='" + categoryID +"'";
			Statement st;
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getRole );
				while(resultSet.next())
				{
					result.append(resultSet.getString("title")+"("+resultSet.getString("language")+");");;
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result.toString();

	    }
	    
	    public static String getCategoryTitle(String categoryID, int language){
	    	categoryID = Utility.squote2dquote(categoryID);
			StringBuffer result = new StringBuffer();
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getRole = "select title from categoryObject where categoryID='" + categoryID +"' and language='" + lang +"'";
			Statement st;
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getRole );
				while(resultSet.next())
				{
					result.append(resultSet.getString("title")+"("+resultSet.getString("language")+");");;
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result.toString();

	    }
		
		public static String getName(String knowledgeID, int language,int type) {
			// TODO Auto-generated method stub
			knowledgeID = Utility.squote2dquote(knowledgeID);
			String result = null;
			String getKnowledgeName = null;
			String knowledgeName = null;
			
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(Utility.checkOntology("roleOntology", type , "precursorNum", knowledgeObject, "subsequenceNum", "is")){
				
				if(type == Definition){
					getKnowledgeName = "select knowledgeName from concept where conceptID='" + knowledgeID +"'";
				}else{
					getKnowledgeName = "select knowledgeName from knowledge where knowledgeID='" + knowledgeID +"'";
				}
			
				Statement st;
				try{
					st = con.createStatement();
					resultSet = st.executeQuery( getKnowledgeName );
					//System.out.println( "getKnowledgeName³É¹¦!" );
					//System.out.println( "----------------!" );
					while(resultSet.next())
					{
						knowledgeName = resultSet.getString("knowledgeName");
					}
				
					String getName = "select name from knowledgeName where knowledgeName='" + Utility.squote2dquote(knowledgeName) + "' and language='"+ lang +"'";
					
					resultSet = st.executeQuery( getName );
					//System.out.println( "getName³É¹¦!" );
					//System.out.println( "----------------!" );
					while(resultSet.next())
					{
						result = resultSet.getString("name");
					}
				
				
					resultSet.close();
					st.close();
					con.close();
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				
				 String getName = "select name from categoryObject where categoryID='" + knowledgeID +"' and language='"+lang+"'";
					Statement st;
					try{
						st = con.createStatement();
						resultSet = st.executeQuery( getName );
						while(resultSet.next())
						{
							result = resultSet.getString("name");
						}
						
						resultSet.close();
						st.close();
						con.close();
					}catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				
				
			}
				
			return result;
		}
		
		public static Vector<String> getCategoryID(String user, String role, String name){

			Vector<String> result = new Vector<String>(1,1);

			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			
			String getID = "select distinct categoryID from categoryObject " 
				+ (name.equals("*")&&role.equals("*")&&user.equals("*")?"":"where ")
				+ (!name.equals("*")?QueryPanel.queryForLogic(name, "name"):"") 
				+ (!role.equals("*")?(!name.equals("*")?"and ":"")+QueryPanel.queryForLogic(role, "role"):"")
				+ (!user.equals("*")?(!name.equals("*")||!role.equals("*")?"and ":"")+QueryPanel.queryForLogic(user, "userName"):"");
			Statement st;
			System.out.println(getID);
			
			try{
				st = con.createStatement();
				resultSet = st.executeQuery( getID );
				while(resultSet.next())
				{
					result.add(resultSet.getString("categoryID"));;
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return result;
		}

		
		public static String getKnowledgeNameFromInput(String name){
			String result = null;
		    Vector<String> nameList = Utility.getItemsBySemicolon(name);
		    for(int i = 0; i < nameList.size(); i++){
		    	Vector<String> termSet = Utility.generateTermSet(nameList.get(i));
		    	if(Utility.deleteSpace(termSet.get(1)).equals("english")){
		    	    result = termSet.get(0);
		    	    break;
		    	}
		    }

		    if(result==null){
		    	result = Utility.generateTermSet(nameList.get(0)).get(0);
		    }
			
			return result;
		}
		
		/**
		 * 
		 * @param userName
		 * @param role : or(A,B,C)
		 * @param name : or()
		 * @return
		 */
		public static Vector<String> getKnowledgeID(String userName, String role, String name ){
			name = Utility.squote2dquote(name);
			Vector<String> result = new Vector<String>(1,1);
			ResultSet resultSet = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			String getKnowledgeName = null;
			Vector<String> roleList = new Vector<String>(1,1);
			if(role.indexOf("(")!=-1||role.indexOf("[")!=-1){
				roleList = Utility.generateTermSetWithSpace(role, '[', ']');
			}else{
				roleList.add("v");
				roleList.add(role);
			}
			
			Statement st;
			getKnowledgeName = "select distinct knowledgeName from knowledgeName " + (name.equals("*")&&role.equals("*")?"":"where ")+
			(!name.equals("*")?QueryPanel.queryForLogic(name, "name"):"") 
			+ (!role.equals("*")?(!name.equals("*")?" and ":"")+QueryPanel.queryForLogic(role, "role"):"");
			
			System.out.println(getKnowledgeName);
				try{
					st = con.createStatement();
					resultSet = st.executeQuery( getKnowledgeName );
					System.out.println( "getKnowledgeName³É¹¦!" );
					System.out.println( "----------------!" );
					while(resultSet.next())
					{
						for(int j =1; j < roleList.size(); j++){
							result.add(new NodeInfo(userName,Utility.getEnglishRole(roleList.get(j)),resultSet.getString("knowledgeName")).getKnowledgeID());
						}
						
					}
									
					
					resultSet.close();
					st.close();
					con.close();
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			return result;
		}
		
		
		
		
		/**
		 * get the formal representation of the definition,theorem 
		 * A;B;C;=>D
		 * A;B;C;D<=>E
		 * @param objectID
		 * @param type
		 * @return
		 */
		public static String getFormalRep(String objectID, int type) {
			// TODO Auto-generated method stub
			System.out.println("break point: " + objectID);
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getbody = null;
			String getobjective = null;
			String getrelation = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(type == Definition){
				getbody = "select formalDefinition from concept_formalDefinition where objectID='"+objectID+"'";
				getobjective = "select instance from concept_formalDefinition where objectID='"+objectID+"'";
				String relation = "\u225D";
		        Statement st;
				try{
					st = con.createStatement();
					ResultSet rs = st.executeQuery( getobjective);
					while(rs.next())
					{
						result = rs.getString("instance");
					}
					ResultSet resultSet = st.executeQuery( getbody);
					while(resultSet.next())
					{
						result = result  + relation + resultSet.getString("formalDefinition");
					}
					rs.close();
					resultSet.close();
					st.close();
					con.close();
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(result.trim().equals(relation)){
					result = null;
				}
				
			}else{
				getbody = "select hypothesis from knowledge_formalRepresentation where objectID='" + objectID +"'";
				getobjective = "select objective from knowledge_formalRepresentation where objectID='" + objectID +"'";
				getrelation = "select relation from knowledge_formalRepresentation where objectID='" + objectID +"'";
		        Statement st;
				try{
					st = con.createStatement();
					ResultSet rs = st.executeQuery( getbody);
					while(rs.next())
					{
						result = rs.getString("hypothesis");
					}
					/*
					ResultSet rs1 = st.executeQuery(getrelation);
					while(rs1.next()){
						int t = Integer.parseInt(rs1.getString("relation"));
						if(t>constants.GTextbookConstants.Formal_Logic_Relation.size()||t==0){
							result = result + "=>";
						}
					}
					*/
					
					
					ResultSet resultSet = st.executeQuery( getobjective );
					while(resultSet.next())
					{
						String objective = resultSet.getString("objective");
						result = result + (objective.indexOf("<=>")!=-1?objective:"=>"+objective);
					}
					rs.close();
					resultSet.close();
					st.close();
					con.close();
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				if(result.trim().equals("=>")||result.trim().equals("<=>")){
					result = null;
				}
			}

				
			return result;
		}

		public static String getAlgScript(String objectID, String version){
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getAlgScript = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getAlgScript = "select algebraicScript from concept_algebraicScript where objectID='"+objectID+"' and version='" + version +"'";
			
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getAlgScript );
				while(resultSet.next())
				{
					result = resultSet.getString("algebraicScript");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getDiagramScript(String objectID, String version){
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getScript = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getScript = "select diagramScript from concept_diagramScript where objectID='"+objectID+"' and version='" + version +"'";
			
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getScript );
				while(resultSet.next())
				{
					result = resultSet.getString("diagramScript");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getTranslationScript(String objectID, String version){
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getScript = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getScript = "select translationScript from concept_translationScript where objectID='"+objectID+"' and language='" + version +"'";
			
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getScript );
				while(resultSet.next())
				{
					result = resultSet.getString("translationScript");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getNdgCondition(String objectID, String version, int type){
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getNdgCondition = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(type == Definition){
				getNdgCondition = "select ndgCondition from concept_ndgCondition where version='" + version + "' and objectID='" + objectID +"'";
			}else{
				getNdgCondition = "select ndgCondition from knowledge_ndgCondition where version='" + version + "' and objectID='" + objectID +"'";
				
			}
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getNdgCondition );
				while(resultSet.next())
				{
					result = resultSet.getString("ndgCondition");
					//System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			if(result == null||result==""){
				result = "null";
			}else{
				if(Utility.deleteSpace(result)==""){
					result = "null";
				}
			}
			return result;
		}

		
		public static String getAlgRep(String objectID, String version, int type) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getAlgRep = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(type == Definition){
			
			}else{
				getAlgRep = "select algebraicRepresentation from knowledge_algebraicRepresentation where objectID='"+objectID+"' and version='" + version +"'";
			}
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getAlgRep );
				System.out.println( "getAlgRep³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("algebraicRepresentation");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}

		public static String getDiagramInstruction(String objectID, String version, int type) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			version = Utility.squote2dquote(version);
			String result = null;
			String getInstruction = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			if(type == Axiom || Utility.checkOntology("roleOntology", type, "precursorNum", Assertion, "subsequenceNum", "is")
					||type == Problem ||type == Example || type == Exercise){
				getInstruction = "select diagramInstruction from knowledge_diagramInstruction where objectID='"+objectID+"' and version='" + version +"'";
			}
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getInstruction );
				System.out.println( "getInstruction³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("diagramInstruction");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}

		public static String getNaturalRep(String objectID, int language) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getAlgRep = null;
			
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
	    	 String getNaturalRep = "select naturalRepresentation from naturalRepresentation where objectID='"+objectID+"' and language='" + lang +"'";
				
	        Statement st;
			try{
				st = con.createStatement();
			     ResultSet resultSet = st.executeQuery( getNaturalRep );
					System.out.println( "getNaturalRep³É¹¦!" );
					System.out.println( "----------------!" );
					while(resultSet.next())
					{
						result = resultSet.getString("naturalRepresentation");
					}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}

/*
		public static String getStaticFigurePath(String objectID, String name) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			name = Utility.squote2dquote(name);
			String result = null;
			String getStaticFigPath = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getStaticFigPath = "select localPath from staticFigure where objectID='" + objectID +"' and name='" + name +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getStaticFigPath );
				System.out.println( "getStaticFigPath³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = "file:///"+resultSet.getString("localPath");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
	*/	
		public static Vector<String> getAllStaticFigurePath(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			Vector<String> result = new Vector<String>(1,1);
			String getStaticFigPath = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getStaticFigPath = "select name,localPath from staticFigure where objectID='" + objectID +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getStaticFigPath );
				System.out.println( "getStaticFigPath³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result.add(resultSet.getString("name")+";"+"file:///"+resultSet.getString("localPath"));
					//System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static Vector<String> getAllStaticFigure(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			Vector<String> result = new Vector<String>(1,1);
			String getStaticFig = "select name,format,staticFigure from staticFigure where objectID='" + objectID +"'";
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
	        Statement st;
			try{
				
 
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getStaticFig );
				System.out.println( "getStaticFigure and generate files!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					String name = resultSet.getString("name");
					String figName = objectID+"."+name+"."+resultSet.getString("format");
					String otPath = constants.GTextbookConstants.TEXTBOOK_DIRECTORY+"/source/figure/"+figName;
				    File fot = new File(otPath);  
				    if (!fot.exists()) {  
				    	fot.createNewFile(); // 如果文件不存在，则创建  
				    }
				    	FileOutputStream fos = new FileOutputStream(fot);  
					    InputStream  is = resultSet.getBinaryStream("staticFigure");  
					    int size = 0; 
					    byte[] Buffer = new byte[constants.GTextbookConstants.figureByteSize];  
					    while ((size = is.read(Buffer)) != -1) {  
					      // System.out.println(size);  
					      fos.write(Buffer, 0, size);  
					    } 
				      
					result.add(name+";"+"file:///"+otPath);
					//System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getGGBFigure(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getGGBFig = "select name,localPath,dynamicFigure from dynamicFigure where objectID='" + objectID +"'";
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getGGBFig );
				System.out.println( "getGGBFigure and generate files!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					String localPath = resultSet.getString("localPath");
					if(localPath!=null && localPath.trim().length()!=0){
						String figName = objectID+"."+ resultSet.getString("name") +".ggb";
						String otPath = constants.GTextbookConstants.TEXTBOOK_DIRECTORY+"/source/ggb/"+figName;
					    File fot = new File(otPath);  
						    if (!fot.exists()) {  
						    	fot.createNewFile(); // 如果文件不存在，则创建  
						    }  
						    	FileOutputStream fos = new FileOutputStream(fot);  
							    InputStream  is = resultSet.getBinaryStream("dynamicFigure");  
							    int size = 0; 
							    byte[] Buffer = new byte[constants.GTextbookConstants.ggbfigureByteSize];  
							    while ((size = is.read(Buffer)) != -1) {  
							      // System.out.println(size);  
							      fos.write(Buffer, 0, size);  
							    } 
						    
						result = "file:///"+otPath;
						//System.out.println(result);
					}
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getStaticFigure(String objectID, String name, String directory) {
			// TODO Auto-generated method stub
			String result = null;
			String getStaticFig, getFormat = null;
			File file = null;
			FileOutputStream fos = null;
			InputStream is = null;
			byte[] Buffer = new byte[4096];
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getStaticFig = "select staticFigure from staticFigure where objectID='" + Utility.squote2dquote(objectID) +"' and name='" + Utility.squote2dquote(name) +"'";
			getFormat = "select format from staticFigure where objectID='" + Utility.squote2dquote(objectID) +"' and name='" + Utility.squote2dquote(name) +"'";
			String format = null;
	        Statement st;
			try{
				st = con.createStatement();
				ResultSet rs = st.executeQuery(getFormat);
				while(rs.next()){
					format = rs.getString("format");
				}
				
				ResultSet resultSet = st.executeQuery( getStaticFig);
				System.out.println( "getStaticFig³É¹¦!" );
				System.out.println( "----------------!" ); 
				while(resultSet.next())
				{
					file = new File(directory+"/"+objectID+"."+name+"."+format);   
					if (!file.exists()) {    
						file.createNewFile(); // Èç¹ûÎÄ¼þ²»´æÔÚ£¬Ôò´´½¨   
					}   
						fos = new FileOutputStream(file);   
						is = resultSet.getBinaryStream("staticFigure");   
						int size = 0;      
						while ((size = is.read(Buffer)) != -1) {    
							// System.out.println(size);    
							fos.write(Buffer, 0, size);   
						}
					
				}
				
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
	  
		
		public static String getDynamicFigurePath(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getAlgRep = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			String getDynamicFig = "select localPath from dynamicFigure where objectID='" + objectID +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getDynamicFig );
				System.out.println( "getDynamicFig³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = "file:///"+resultSet.getString("localPath");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getVisualizationPath(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			String getVisualizationPath = "select localPath from visualization where objectID='" + objectID +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getVisualizationPath );
				//System.out.println( "getDynamicFig³É¹¦!" );
				//System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("localPath");
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		
		public static String getProof(String objectID, int language) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getProof = null;
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getProof = "select proof from proof where objectID='" + objectID +"' and language='" + lang + "'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getProof );
				System.out.println( "getProof³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("proof");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}
		
		public static String getExercise(String objectID, int language) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getProof = null;
			String lang =null;
			if(language == English){
				lang = "english";
			}else if(language == Chinese){
				lang = "中文";
			}
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getProof = "select exercise from exercise where objectID='" + objectID +"' and language='" + lang + "'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getProof );
				System.out.println( "getExercise³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("exercise");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}

		public static String getIntroduction(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getIntroduction = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getIntroduction = "select introduction from introduction where objectID='" + objectID +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getIntroduction );
				System.out.println( "getIntroduction³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("introduction");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}


		public static String getRemark(String objectID) {
			// TODO Auto-generated method stub
			objectID = Utility.squote2dquote(objectID);
			String result = null;
			String getRemark = null;
			Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

			getRemark = "select remark from remark where objectID='" + objectID +"'";

	        Statement st;
			try{
				st = con.createStatement();
				ResultSet resultSet = st.executeQuery( getRemark );
				System.out.println( "getRemark³É¹¦!" );
				System.out.println( "----------------!" );
				while(resultSet.next())
				{
					result = resultSet.getString("remark");
					System.out.println(result);
				}
				resultSet.close();
				st.close();
				con.close();
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			return result;
		}


		
		
		
		
		 /** Remove the temptarory file. */
		 
		 public static void deleteFile(GTextbook theApp, IndexTreeNode node){
			 
			 String url = ((NodeInfo)(node.getUserObject())).getUrl();
			 
			 File file = new File(((IndexTreeView)(((GTView)(theApp.getView())).getIndexTabbedPane().getSelectedComponent())).getIndexTree().getTextbookPresentationDirectory() +"/"+url);
			 
			 //System.out.println(file);
			 if(file.exists()){
				 file.delete();
			 }	 	 
		 }
		 
		 
		 /**insert information into the database**/
			public static String insert1(String tableName, String arg){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg) + "')";
			}
			public static String insert2(String tableName, String objectID, String word){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(objectID)+ "','" + Utility.squote2dquote(word) + "')";
			}
			
			public static String insert3(String tableName, String arg1, String arg2, String arg3){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3)+ "')";
			}
			
			public static String insert4(String tableName, String arg1, String arg2, String arg3, String arg4){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3) + "','" + Utility.squote2dquote(arg4) + "')";
			}

			public static String insert5(String tableName, String arg1, String arg2, String arg3, String arg4, String arg5){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3) + "','" + Utility.squote2dquote(arg4) + "','" + Utility.squote2dquote(arg5) +"')";
			}
			
			
			public static String insert6(String tableName, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3) + "','" + Utility.squote2dquote(arg4) + "','" + Utility.squote2dquote(arg5) + "','" + Utility.squote2dquote(arg6) +"')";
			}
	  
			public static String insert7(String tableName, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6,String arg7){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3) + "','" + Utility.squote2dquote(arg4) + "','" + Utility.squote2dquote(arg5) + "','" + Utility.squote2dquote(arg6) +"','" + Utility.squote2dquote(arg7) +"')";
			}
			
			public static String insert9(String tableName, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6,String arg7, String arg8, String arg9){
				return "INSERT INTO " + tableName+" VALUES ('" + Utility.squote2dquote(arg1)+ "','" + Utility.squote2dquote(arg2) + "','" + Utility.squote2dquote(arg3) + "','" + Utility.squote2dquote(arg4) + "','" + Utility.squote2dquote(arg5) + "','" + Utility.squote2dquote(arg6) +"','" + Utility.squote2dquote(arg7) +"','" + Utility.squote2dquote(arg8) +"','" + Utility.squote2dquote(arg9) +"')";
			}
			
			/**insert static figure into the database**/
			public static boolean insertStaticFigure(FigurePage figurePage, String objectID){
				boolean result = true;
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				 
			    try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			  	    	//for static figure
			  	    	int staticFigureNum = figurePage.getImageDropPanel().getFigureList().size();
			  	    	for(int j = 0; j < staticFigureNum; j++){
			  	    		FigurePanel figurePanel = figurePage.getImageDropPanel().getFigureList().get(j);
			  	    		String path = figurePanel.getLocalPath();
			  	    		String format = path.substring(path.lastIndexOf('.')+1,path.length());
			  	    		System.out.println(format);
			  	    		if(figurePanel.getFigName().getText().trim()!=""&&figurePanel.getFigName().getText().trim().length()!=0){
				  	    		String figureName = Utility.squote2dquote(figurePanel.getFigName().getText());
			  	    	    	String staticFigurePath = Utility.squote2dquote(figurePanel.getLocalPath());
			  	    		
				 
			  	    	    	
				  	    	    File figureFile = new File(path);
				  	    	    if(figureFile.exists()){
				  	    	    	FileInputStream fis = new FileInputStream(figureFile);
				  	    	    	PreparedStatement ps=con.prepareStatement("INSERT INTO staticFigure(objectID,name,staticFigure,format,localPath) VALUES ('"+ Utility.squote2dquote(objectID) + "','" + figureName +"',?,'" + format + "','" + staticFigurePath +"')");
	
				  	    	    	ps.setBinaryStream(1,fis,(int)figureFile.length());
	
				  	    	    	ps.executeUpdate();
				  	    	    	fis.close();
				  	    	    	ps.close();
				  	    	    	System.out.println("Success,You Have Insert an Image Successfully");
				  	    	    }
			  	    	    
		  	    	    	
		  	    	    	 /*
		  	    	    	//File outputFile = new File("D:/GTextbook/a.jpg");
		  	    	    	//FileOutputStream fot = new java.io.FileOutputStream(outputFile);     
		  	    	        int flength = (int) figureFile.length(); //**读入文件的字节长度      
		  	    	        byte a[] = new byte[flength];     
		  	    	        int i = 0;     
		  	    	        int itotal = 0;     
		  	    	        //* 将文件读入字节数组     
		  	    	        for (; itotal < flength; itotal = i + itotal) {     
		  	    	        	i = fin.read(a, itotal, flength - itotal);     
		  	    	        }     
		  	    			
		  	    			//fot.write(a); 
			  	    		//fot.close();
		  	    	        */
			  	    	    /*
			  	    		Statement st = con.createStatement();
			  	    		String getStaticFigure = "INSERT INTO staticFigure(objectID,name,format,localPath) VALUES ('"+ Utility.squote2dquote(objectID) + "','" + figureName +"','" + format + "','" + staticFigurePath +"')";
			  	    		st.executeUpdate(getStaticFigure);
			  	    		st.close();
			  	    		*/
			  	    		}
			  	    	}
			          
			          con.close();
			          
	  	    	
			    }	      
			    catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
			    System.out.println(result);
			    return result;
			}
			
			/**insert static figure into the database**/
			public static boolean insertGGBFigure(String name, String localPath, String objectID){
				boolean result = true;
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				 
			    try{    
			  	    		
				  	   String figureName = Utility.squote2dquote(name);
				  	   String path = Utility.squote2dquote(localPath);

				  	   if(localPath!=null && localPath.trim().length()!=0){
					  	    File file = new File(localPath);
					  	    if(file.exists()){
					  	    	 FileInputStream fis = new FileInputStream(file);
					  	    	 PreparedStatement ps=con.prepareStatement("INSERT INTO dynamicFigure(objectID,name,dynamicFigure,localPath) VALUES ('"+ Utility.squote2dquote(objectID) + "','" + figureName +"',?,'" + path +"')");
		
					  	    	 ps.setBinaryStream(1,fis,(int)file.length());
		
					  	    	 ps.executeUpdate();
					  	    	 fis.close();
					  	    	 ps.close();
					  	    	 System.out.println("Success,You Have Insert a ggb file Successfully");
					  	    }
			  	    	    
				  	   }
			          con.close();
			          
	  	    	
			    }	      
			    catch(Exception err){
			    	 result = false;
			         err.printStackTrace(System.out);
			         
			      }
			    System.out.println(result);
			    return result;
			}
			
			// insert the relations
			public static boolean insertRelation(RelationPanel relationPanel, String objectID, Vector<String> newRelation){
				boolean result = true;
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				 
			    try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          int relationNum = relationPanel.getRelationTabbedPane().getTabCount();
			          for(int j = 0; j < relationNum; j++){
			        	  RelationPage page = (RelationPage)(relationPanel.getRelationTabbedPane().getComponentAt(j));
			        	  String relationType = page.getRelationList().getComboBox().getSelectedItem().toString();
			        	  Vector<String> preList = Utility.getItemsBySemicolon(page.getPrePanel().getTextArea().getText());
			        	  Vector<String> subList = Utility.getItemsBySemicolon(page.getSubPanel().getTextArea().getText());
			        	  
			        	  //parse the list of the relations
			        	  for(int i = 0; i<preList.size(); i++){
				        	  	st.executeUpdate(insert3("KOstructure", preList.get(i), objectID, relationType));
			        	  }


			        	  for(int i = 0; i<subList.size(); i++){
			        	  		st.executeUpdate(insert3("KOstructure", objectID, subList.get(i), relationType));
			        	  }
	  	    		
			        	  	if(!Utility.existIn(relationType, Relation_Type)){
			        	  			Relation_Type.add(relationType);
			        	  			newRelation.add(relationType);
			        	  		}
			          	}
			          
			          st.close();
			          con.close();
	  	    	
			    }	      
			    catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
			    
			    return result;
			}
			
			
			/** fetch the relations among knowledge objects **/
			public static boolean fetchRelation(JTabbedPane relationTabbedPane, String objectID){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
			    try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          ResultSet resultSet = st.executeQuery("select distinct relationType from KOstructure where precursor='"+objectID+"' or subsequence='" + objectID +"'"); 
			          Vector<String> relationTypes = new Vector<String>(1,1);
			          while(resultSet.next()){
			        	  relationTypes.add(resultSet.getString("relationType"));
			          }
			          if(relationTypes.size()>0){
				          relationTabbedPane.remove(0);      	  
			          }

			          for(int i=0;i<relationTypes.size();i++){
			        	  String relationType = relationTypes.get(i);
			              StringBuffer preString = new StringBuffer();
			              StringBuffer subString = new StringBuffer();
			        	  ResultSet preSet = st.executeQuery("select precursor from KOstructure where subsequence='"+objectID+"' and relationType='"+relationType+"'");
			        	  while(preSet.next()){
		        			  preString.append(preSet.getString("precursor")+";");	
		        		  }
			        	  ResultSet subSet = st.executeQuery("select subsequence from KOstructure where precursor='"+objectID+"' and relationType='"+relationType+"'");
		        		  
		        		  while(subSet.next()){
		        			  subString.append(subSet.getString("subsequence")+";");	

		        		  }
		        		  System.out.println(preString + "  "+subString);
	        			  RelationPage relationPage = new RelationPage(relationType,language.getNum());
	        			  relationPage.getPrePanel().getTextArea().setText(preString.toString());
	        			  relationPage.getSubPanel().getTextArea().setText(subString.toString());
	        			  relationPage.getRelationList().getComboBox().setSelectedItem(relationType);
	        			  relationTabbedPane.addTab(relationType, relationPage);
	        			  
	        			  preSet.close();
	        			  subSet.close();
			          }
			          
			          resultSet.close();			          
			          st.close();
			          con.close();
	  	    	
			    }	      
			    catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				return result;
			}
		
			
			
			/**fetch information of each knowledge object for modification**/ 
			public static boolean fetchNaturalRep(JTabbedPane page, String objectID){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	 ResultSet resultSet = st.executeQuery("select language from naturalRepresentation where objectID='"+objectID+"'"); 
			        	 page.remove(0);
			        	 while(resultSet.next()){
			        		  String version = resultSet.getString("language");
			        		  Statement stbuff = con.createStatement();
			        		  ResultSet buff = stbuff.executeQuery("select naturalRepresentation from naturalRepresentation where objectID='"+objectID+"' and language='"+Utility.squote2dquote(version)+"'");
			        		  while(buff.next()){
			        			  TextTabbedPage textPage = new TextTabbedPage(version,language.getNum(),Advanced_Text_Area_Dimension);
			        			  textPage.getTextArea().setText(buff.getString("naturalRepresentation"));
			        			  page.addTab(version, textPage);
			        		  }
			        		  stbuff.close();
			        		  buff.close();

			        	  }
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();
			          
			          
				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			
			/**fetch information of each knowledge object for modification**/ 
			public static boolean fetchProof(JTabbedPane page, String objectID){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	 ResultSet resultSet = st.executeQuery("select language from proof where objectID='"+objectID+"'"); 
			        	 page.remove(0);
			        	 while(resultSet.next()){
			        		  String version = resultSet.getString("language");
			        		  Statement stbuff = con.createStatement();
			        		  ResultSet buff = stbuff.executeQuery("select proof from proof where objectID='"+objectID+"' and language='"+version+"'");
			        		  while(buff.next()){
			        			  TextTabbedPage textPage = new TextTabbedPage(version,language.getNum(),Proof_Area_Dimension);
			        			  textPage.getTextArea().setText(buff.getString("proof"));
			        			  page.addTab(version, textPage);
			        		  }
			        		  stbuff.close();
			        		  buff.close();

			        	  }
			        	 
			        	 //ÈôÊý¾Ý¿âÖÐÃ»ÓÐÐÅÏ¢£¬ÔòÐÂ½¨Ò³
			        	 if(page.getTabCount()==0){
		        			  TextTabbedPage textPage = new TextTabbedPage("english",language.getNum(),Advanced_Text_Area_Dimension);
		        			  textPage.getTextArea().setText("");
		        			  page.addTab("english", textPage);
			        	 }
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();
			          
			          
				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			
			public static boolean fetchExercise(JTabbedPane page, String objectID){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	 ResultSet resultSet = st.executeQuery("select language from exercise where objectID='"+objectID+"'"); 
			        	 page.remove(0);
			        	 while(resultSet.next()){
			        		  String version = resultSet.getString("language");
			        		  Statement stbuff = con.createStatement();
			        		  ResultSet buff = stbuff.executeQuery("select exercise from exercise where objectID='"+objectID+"' and language='"+version+"'");
			        		  while(buff.next()){
			        			  TextTabbedPage textPage = new TextTabbedPage(version,language.getNum(),Proof_Area_Dimension);
			        			  textPage.getTextArea().setText(buff.getString("exercise"));
			        			  page.addTab(version, textPage);
			        		  }
			        		  stbuff.close();
			        		  buff.close();

			        	  }
			        	 
			        	 //ÈôÊý¾Ý¿âÖÐÃ»ÓÐÐÅÏ¢£¬ÔòÐÂ½¨Ò³
			        	 if(page.getTabCount()==0){
		        			  TextTabbedPage textPage = new TextTabbedPage("english",language.getNum(),Advanced_Text_Area_Dimension);
		        			  textPage.getTextArea().setText("");
		        			  page.addTab("english", textPage);
			        	 }
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();
			          
			          
				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			
			
			
			public static boolean fetchCategoryNote(JTabbedPane page, String categoryID){

				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	 ResultSet resultSet = st.executeQuery("select language from categoryObject where categoryID='"+Utility.squote2dquote(categoryID)+"'"); 
			        	 page.remove(0);
			        	 while(resultSet.next()){
			        		  String version = resultSet.getString("language");
			        		  Statement stbuff = con.createStatement();
			        		  ResultSet buff = stbuff.executeQuery("select note from categoryObject where categoryID='"+Utility.squote2dquote(categoryID)+"' and language='"+Utility.squote2dquote(version)+"'");
			        		  while(buff.next()){
			        			  TextTabbedPage textPage = new TextTabbedPage(version,language.getNum(),Advanced_Text_Area_Dimension);
			        			  textPage.getTextArea().setText(buff.getString("note"));
			        			  page.addTab(version, textPage);
			        		  }
			        		  stbuff.close();
			        		  buff.close();

			        	  }

			        	 //ÈôÊý¾Ý¿âÖÐÃ»ÓÐÐÅÏ¢£¬ÔòÐÂ½¨Ò³
			        	 if(page.getTabCount()==0){
		        			  TextTabbedPage textPage = new TextTabbedPage("english",language.getNum(),Advanced_Text_Area_Dimension);
		        			  textPage.getTextArea().setText("");
		        			  page.addTab("english", textPage);
			        	 }
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();

				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			
			public static boolean fetchKeyWords(JTextArea page, String objectID){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	  ResultSet resultSet = st.executeQuery("select keyWord from keyWords where objectID='"+objectID+"'");
			              StringBuffer bufKeyWords = new StringBuffer();
			        	  while(resultSet.next()){
			        		  if(!resultSet.getString("keyWord").equals(""))
			        		  	bufKeyWords.append(resultSet.getString("keyWord")+";");	  
			        	  }
			        	  page.setText(bufKeyWords.toString()); 
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();
			          
			          
				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			


			
			public static boolean fetchTabbedPage(JTabbedPane tabbedPane, String objectID, String table, String version, String content){
				objectID = Utility.squote2dquote(objectID);
				boolean result = true;
				 //connect to the database
				Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				
				try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

			          Statement st = con.createStatement();
			          //System.out.println( "´´½¨Statement³É¹¦!" );
			          
			        	 ResultSet resultSet = st.executeQuery("select " + version +" from " + table + " where objectID='"+ objectID +"'"); 
			        	 tabbedPane.remove(0);
			        	 while(resultSet.next()){
			        		  String tab = resultSet.getString(version);
			        		  Statement stbuff = con.createStatement();
			        		  ResultSet buff = stbuff.executeQuery("select " + content + " from " + table +" where objectID='"+objectID+"' and " + version + "='"+ tab +"'");
			        		  while(buff.next()){
			        			  TextTabbedPage textPage;
			        			  if(content.equals("diagramInstruction")||content.equals("diagramScript")){
			        				  textPage = new TextTabbedPage(DialogConstants.Diagram_Instruction,tab,language.getNum(),Advanced_Text_Area_Dimension);
			        			  }else{
			        				  textPage = new TextTabbedPage(tab,language.getNum(),Advanced_Text_Area_Dimension);
			        			  }
			        			  textPage.getTextArea().setText(buff.getString(content));
			        			  tabbedPane.addTab(tab, textPage);
			        		  }
			        		  stbuff.close();
			        		  buff.close();
			        	  }
			        	 
			        	 resultSet.close();
			        	 st.close();
			        	 con.close();
			          
			          
				}catch(Exception err){
			          err.printStackTrace(System.out);
			          result = false;
			      }
				
				return result;
			}
			

			

			
			
			/**modify the display of knowledge object in the index tree**/
			public static boolean modifyView(GTextbook theApp, IndexTreeNode node, String knowledgeName){
				boolean result = true;
				
				//remove the temp xml file
				
				Utility.deleteFile(theApp, node);
				
				//modify the node information
				NodeInfo newInfo = new NodeInfo(((NodeInfo)(node.getUserObject())).getRole(), knowledgeName, language.getNum());
				node.setUserObject(newInfo);
				node.setName(newInfo.toString());
				//set it is true that we have modified the current textbook
				theApp.getView().getChangedList().set(theApp.getModel().getCurrentModelIndex(), true);
				return result;
			}
			
			
			/** check whether role1 is role2 by using the roleOntology**/
			
			public static boolean checkOntology(String table, String A, String AField, String B, String BField, String relation){
				boolean result = false;
				 //initial the array list for the text field
		        Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
		        try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 
		        	
		            Statement st = con.createStatement();
		            //System.out.println( "´´½¨Statement³É¹¦!" );
		            
		            String sql = "select " + BField + " from " + table + " where " + AField + "='"+A+"' and relationType='"+relation+"'";
		            
		            ResultSet rs = st.executeQuery(sql);
            		while(rs.next())
            		{
            			String sub = rs.getString(BField);
            			if(sub.equals(B)){
            				result = true;
            			}else{
            				result = checkOntology(table,sub,AField,B,BField,relation);
            			}
            				
            		}
            		rs.close();
				
		            st.close();
		            con.close();
		        }
		        catch(Exception err){
		            err.printStackTrace(System.out);
		        }
				
				
				return result;
			}
			
			public static boolean checkOntology(String table, int A, String AField, int B, String BField, String relation){
				boolean result = false;
				 //initial the array list for the text field
		        Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
		        try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 
		        	
		            Statement st = con.createStatement();
		            //System.out.println( "´´½¨Statement³É¹¦!" );
		            
		            String sql = "select " + BField + " from " + table + " where " + AField + "='"+A+"' and relationType='"+relation+"'";
		            
		            ResultSet rs = st.executeQuery(sql);
            		while(rs.next())
            		{
            			int sub = rs.getInt(BField);
            			if(sub==B){
            				result = true;
            			}else{
            				result = checkOntology(table,sub,AField,B,BField,relation);
            			}
            				
            		}
            		rs.close();
				
		            st.close();
		            con.close();
		        }
		        catch(Exception err){
		            err.printStackTrace(System.out);
		        }
				
				
				return result;
			}
			
			
			

			public static ArrayList<IndexTreeNode> bookEnumeration(IndexTreeNode root){
				ArrayList<IndexTreeNode> result = new ArrayList();
				
				if(root.isLeaf()){
					result.add(root);
				}else{
					result.add(root);
					for(int i = 0; i<root.getChildCount(); i++){
						result.addAll(result.size(),bookEnumeration((IndexTreeNode)root.getChildAt(i)));
					}
				}
				
				
				
				return result;
			}
			
			public static Vector[] generateRelatedNodes(String knowledgeID){
		    	Vector<String> preList = new Vector<String>(1,1);
		    	Vector<String> subList = new Vector<String>(1,1);
		    	//constants.GTextbookConstants.authorContext.update();
		    	Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
				try{
					Statement st = con.createStatement();
					
					int count = constants.GTextbookConstants.authorContext.getConsistencyCheckingContext().size();
					
					for(int i = 0; i < count; i++){
						String relationType = constants.GTextbookConstants.authorContext.getConsistencyCheckingContext().get(i);
						String getPrecursor = "select distinct KOstructure.precursor from KOstructure, allNode where allNode.nodeID='"+Utility.squote2dquote(knowledgeID)+"' and allNode.objectID=KOstructure.subsequence and KOstructure.relationType='" + relationType + "'";
						String getSub = "select distinct KOstructure.subsequence from KOstructure, allNode where allNode.nodeID='"+Utility.squote2dquote(knowledgeID)+"' and allNode.objectID=KOstructure.precursor and KOstructure.relationType='" + relationType + "'";
						String precursorCol = "precursor";
						String subsequenceCol = "subsequence";
						/************************************************
						 * ÒòÎªÓÐµÄ¹ØÏµÊÇ·´ÏòµÄ£¬Òò´ËÒª½«¹ØÏµµÄÇ°ºó¶ÔÏó¶Ôµ÷
						***************************************************/
						if(relationType.equals("inherit")||relationType.equals("Inherit")||relationType.equals("deriveFrom")
								||relationType.equals("decide")||relationType.equals("remarkOn")||relationType.equals("complicate")||relationType.equals("exerciseOf")){
							String buf = null;
							buf = getPrecursor;
							getPrecursor = getSub;
							getSub = buf;
							buf = precursorCol;
							precursorCol = subsequenceCol;
							subsequenceCol = buf;
						}

						ResultSet prers = st.executeQuery(getPrecursor);
						//System.out.println("getpre :" + getPrecursor);
						while(prers.next()){
							//System.out.println("pre: "+prers.getString(precursorCol));
							preList.add(prers.getString(precursorCol));
						}
						
						ResultSet subrs = st.executeQuery(getSub);
						//System.out.println("getsub: "+getSub);
						while(subrs.next()){
							//System.out.println("sub :" + subrs.getString(subsequenceCol));
							subList.add(subrs.getString(subsequenceCol));
						}
						prers.close();
						subrs.close();
						
						
						System.out.println("**********"+relationType+"*****************");
						System.out.println("-----pre------");
						for(int j = 0; j < preList.size();j++){
							System.out.println(preList.get(j));
						}
						System.out.println("-----sub------");
						for(int j = 0; j < subList.size();j++){
							System.out.println(subList.get(j));
						}
						System.out.println("*******************");
				
				}
					st.close();
					con.close();
					
					
				}catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	

				
		    	Vector[] result = {preList,subList};
		    	return result;
		    }
			
			public static void updateRelationMenu(GTextbook theApp,Vector<String> newRelation){
		        //update the list of relation and the checkbox in the menu of GTFrame
			  	  LangMenu relationMiningMenu = theApp.getWindow().getRelationMiningMenu();
			  	  LangMenu consistancyCheckingMenu = theApp.getWindow().getConsistancyCheckingMenu();
			  	//connect to the database
					Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);
					 
				     try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

				          Statement st = con.createStatement();
				          //System.out.println( "´´½¨Statement³É¹¦!" );
				          for(int t = 0; t < newRelation.size(); t++){
				        	  st.executeUpdate(Utility.insert1("relationType", newRelation.get(t)));
				        	  relationMiningMenu.add(new JCheckBoxMenuItem(newRelation.get(t),false));
				        	  consistancyCheckingMenu.add(new JCheckBoxMenuItem(newRelation.get(t),false));
				          }
				          st.close();
				          con.close();	 
				      }
				      catch(Exception err){
				          err.printStackTrace(System.out);	        
				      }
			}
			
			public static void executeBatFile(String path, String filename){
				String command = "cmd /C start /D \""+path+"\" /min " + filename;
				
				try {    
			        Process child = Runtime.getRuntime().exec(command);    
			        InputStream in = child.getInputStream();    
			        int c;    
			        while ((c = in.read()) != -1) {    
			            System.out.print(c);    
			        }    
			        in.close();    
			        try {    
			            child.waitFor();    
			        } catch (InterruptedException e) {    
			            // TODO Auto-generated catch block    
			            e.printStackTrace();    
			        }    
			        //System.out.println("done");    
			    } catch (IOException e) {    
			        // TODO Auto-generated catch block    
			        e.printStackTrace();    
			    }
			}

			public static Engine buildEngine4Maple(CallBacks callback){
				
				 Engine engine;
				 
				  /* build the command line arguments for Maple */
					String a[];
			        a = new String[1];
			        a[0] = "java";
			        
			        try
			        {
			            /* start the Maple session.  Use the Default EngineCallBacks. 
			             * the text Output will be directed to System.out */
			            engine = new Engine(a,callback,null, null );
			            engine.evaluate( "with(geother);");
			            return engine;
			        }
			        catch ( MapleException e1 )
			        {
			            /* if an error occurs, exit */
			        	LangWarningPane.showMessageDialog(null,"Cannot connect to Maple！Cannot use GEOTHER！", "无法连接到Maple！无法使用GEOTHER！", "Auto Proving Disabled", "自动证明不可用", JOptionPane.ERROR_MESSAGE, language.getNum());			
			        	System.out.println(e1);
			            System.out.println( "An exception occured\n" );
			            return null;
			        }  
			}
			
			
			public static String getFormalString4Script(String data, String ndg){
				StringBuffer result = new StringBuffer(10);
				result.append("Script(");
				
				int index = data.indexOf("\u225D");
				
				String instance = data.substring(0,index);
				String body = data.substring(index+1,data.length());
				
				result.append("Definition(" + instance +","+body+","+ndg+")");
				
				
				result.append(")");			
				return result.toString();
			}
			
			
			public static String getFormalString4Multiple(String data,String name, String role){
				StringBuffer result = new StringBuffer(10);
				result.append("Problems(");
				int index = data.indexOf("<=>");
				if(index !=-1 ){
					String hypothesisString = data.substring(0,index);
					String conclusionString = data.substring(index+3,data.length());
					
					result.append(getFormalString4Single(hypothesisString + "=>" +conclusionString, name+"_forward", role));
						
					
					
					Vector<String> H = Utility.getItemsBySemicolon(hypothesisString);
					String newConclusion = H.get(H.size()-1);
					StringBuffer buf = new StringBuffer(20);
					for(int i = 0; i < H.size()-1; i++){
						buf.append(H.get(i)+";");
					}
					buf.append(conclusionString+"=>"+newConclusion);
					
					result.append(","+getFormalString4Single(buf.toString(),name+"_backward",role)+")");
					
				}else{
					index = data.indexOf("=>");
					if(index!=-1){
						String hypothesisString = data.substring(0,index);
						String conclusionString = data.substring(index+2,data.length());
						/*
						Vector<String> C = Utility.getItemsBySemicolon(conclusionString);
						

						if(C.size()<=1){
							result.append(getFormalString4SingleConclusion(hypothesisString+"=>"+C.get(0),name,role));
						}else{
							//¶à¸ö½áÂÛ
							
							for(int j = 0; j < C.size()-1; j++){
								result.append(getFormalString4SingleConclusion(hypothesisString+"=>"+C.get(j),name,role)+",");
								
							}
							result.append(getFormalString4SingleConclusion(hypothesisString+"=>"+C.get(C.size()-1),name,role)+",");
							
						}*/
						
						result.append(getFormalString4Single(data,name,role)+")");
						
						
					}
				}
				
				return result.toString();
			}
			
			
			
			public static String getFormalString4Single(String data, String name, String role){
				StringBuffer result = new StringBuffer(10);
				int index = data.indexOf("=>");
				if(index !=-1){
					String hypothesisString = data.substring(0,index);
					String conclusionString = data.substring(index+2,data.length());
					StringBuffer buf = new StringBuffer(100);
					if(hypothesisString.indexOf("configuration")!=-1){
						buf.append(hypothesisString.replace("configuration", "assume"));
					}else{
						Vector<String> H = Utility.getItemsBySemicolon(hypothesisString);
						buf.append("assume(");
						for(int i = 0; i < H.size()-1; i++){
							buf.append(H.get(i)+",");
						}
						buf.append(H.get(H.size()-1)+")");
					}
					StringBuffer buf1 = new StringBuffer(100);
					if(conclusionString.indexOf("configuration")!=-1){
						buf1.append(conclusionString.replace("configuration", "show"));
					}else{
						Vector<String> C = Utility.getItemsBySemicolon(conclusionString);
						buf1.append("show(");
						for(int i = 0; i < C.size()-1; i++){
							buf1.append(C.get(i)+",");
						}
						buf1.append(C.get(C.size()-1)+")");
					}
					
					result.append("Theorem(" + name + "," + role + "," + buf.toString() + "," + buf1.toString() +")");
					
				}
				return result.toString();
			}
			
			
			public static String getEnglishRole(String role){
				String result = role;
					if(role.equals("定义")){
						result = "Definition";
					}
					else if(role.equals("引理")){
						result = "Lemma";
					}
					else if(role.equals("定理")){
						result = "Theorem";
					}
					else if(role.equals("推论")){
						result = "Corollary";
					}
					else if(role.equals("公理")){
						result = "Axiom";
					}else if(role.equals("猜想")){
						result = "Conjecture";
		
					}
					else if(role.equals("问题")){
						result = "Problem";

					}
					else if(role.equals("例子")||role.equals("例")){
						result = "Example";
						
					}
					else if(role.equals("练习")){
						result = "Exercise";
					
					}
					else if(role.equals("证明")){
						result = "Proof";
						
					}
					else if(role.equals("解答")||role.equals("解")){
						result = "Solution";
						
					}
					else if(role.equals("介绍")||role.equals("引言")){
						result = "Introduction";
						
					}
					else if(role.equals("注释")||role.equals("注")){
						result = "Remark";
						
					}
					else if(role.equals("算法")){
						result = "Algorithm";
						
					}else if(role.equals("类型")){
						result = "Type";				
					}
					return result;
			}
			
			/*
	         * code for generating author condition
	         */
			public static String generateQueryAuthorCondition(String table, String field){
				
				Vector<String> v = new Vector<String>(1,1);
				v.add(constants.GTextbookConstants.authorContext.getUserContext());

		  		int authorContextCount = v.size();
		  		if(authorContextCount>0){
		  			StringBuffer authorCondition = new StringBuffer(20);
		  			authorCondition.append("(");

		  			for(int i = 0; i < authorContextCount-1; i++){
		  				authorCondition.append(table==null?field+"='":table+"."+field+"='")
		  				.append(ui.Utility.squote2dquote(v.get(i))).append("' or ");

		  			}
		  			authorCondition.append(table==null?field+"='":table+"."+field+"='")
		  				.append(ui.Utility.squote2dquote(v.get(authorContextCount-1))).append("')");
		          
	        	
		  			return authorCondition.toString();
		  		}else
		  			return "";
			}
				
			public static String generateQueryRelationTypeCondition(String table, String field){

		  		int consistencyContextCount = constants.GTextbookConstants.authorContext.getConsistencyCheckingContext().size();
		  		if(consistencyContextCount>0){
		  			StringBuffer condition = new StringBuffer(20);
		  			condition.append("(");

		  			for(int i = 0; i < consistencyContextCount-1; i++){
		  				condition.append(table==null?field+"='":table+"."+field+"='")
		  				.append(ui.Utility.squote2dquote(
	        				constants.GTextbookConstants.authorContext.getConsistencyCheckingContext().get(i))).append("' or ");

		  			}
		  			condition.append(table==null?field+"='":table+"."+field+"='")
		  				.append(ui.Utility.squote2dquote(
		  						constants.GTextbookConstants.authorContext.getConsistencyCheckingContext().get(consistencyContextCount-1))).append("')");
		          
	        	
		  			return condition.toString();
		  		}else
		  			return "";
			}
			
			
			/**
			 * 
			 * @param A
			 * @param B
			 * @return A-B
			 */
			public static ArrayList<NodeInfo> getDifferenceOfNodeSet(Vector<NodeInfo> A, IndexTreeNode B){
				ArrayList<NodeInfo> result = new ArrayList<NodeInfo>();
				
				ArrayList<IndexTreeNode> b = Utility.bookEnumeration(B);
				
				boolean flag = false;
				for(int i = 0; i<A.size(); i++){
					flag = false;
					for(int j = 0 ; j < b.size(); j++){
						if(A.get(i).equals((NodeInfo)b.get(j).getUserObject())){
							flag = true;
							break;
						}
						//System.out.println("µÚ" + i + "´Î " +(NodeInfo)b.get(j).getUserObject());
					}
					if(flag == false){
						result.add(A.get(i));
					}
				}
				
				return result;
			}
			
			public static ArrayList<String> getDifferenceOfStringSet(Vector<String> A, IndexTreeNode B){
				ArrayList<String> result = new ArrayList<String>();
				
				ArrayList<IndexTreeNode> b = Utility.bookEnumeration(B);
				
				boolean flag = false;
				for(int i = 0; i<A.size(); i++){
					flag = false;
					for(int j = 0 ; j < b.size(); j++){
						if(A.get(i).equals((NodeInfo)b.get(j).getUserObject())){
							flag = true;
							break;
						}
						//System.out.println("µÚ" + i + "´Î " +(NodeInfo)b.get(j).getUserObject());
					}
					if(flag == false){
						result.add(A.get(i));
					}
				}
				
				return result;
			}
			
			
			/**
			 * 
			 * @param A
			 * @param B
			 * @return A is in B
			 */
			public static boolean isRedundant(NodeInfo A, IndexTreeNode B){
				boolean result = false;
				ArrayList<IndexTreeNode> b = Utility.bookEnumeration(B);
				
				for(int i = 0; i<b.size(); i++){
					
					if(((NodeInfo)b.get(i).getUserObject()).equals(A)){
							result = true;
							break;
					}	
					
					//System.out.println("Redundant:" + b.get(i));
				}	
				
				return result;
			}
			
			/**
			 * get the IndexTreeNode from knowledgeID
			 * @param knowledgeID
			 * @return
			 */
			public static IndexTreeNode getIndexTreeNode(String knowledgeID){
				  IndexTreeNode result = null;
				  Connection con = Utility.createConnection(DatabaseName,DatabaseUserName,DatabasePassWord);

				  String role = null;
				  String name = null;
				  String username = null;
				  
				  try{    //ÕâÀïµÄÒì³£´¦ÀíÓï¾äÊÇ±ØÐèµÄ.·ñÔò²»ÄÜÍ¨¹ý±àÒë! 

		    	          Statement st = con.createStatement();
		    	          //System.out.println( "´´½¨Statement³É¹¦!" );
		    	          
		    	          if(knowledgeID.indexOf("Category")!=-1){
		    	        	  role = Utility.getCategoryRole(knowledgeID, English);
		    	        	  name = Utility.getName(knowledgeID, English, Category);
		    	        	  ResultSet resultSet = st.executeQuery("select author from allNode where nodeID='" + Utility.squote2dquote(knowledgeID) +"'");   	
		    	        	  while(resultSet.next()){
		    	        		  username = resultSet.getString("author");
		    	        	  }	    	    
		    	        	  resultSet.close();
		        	          st.close();
		        	          con.close();
		    	          }else{
		    	        	  ResultSet resultSet = st.executeQuery("select role,name,author from allNode where nodeID='" + Utility.squote2dquote(knowledgeID) +"'");   	
		    	        	  while(resultSet.next()){
		    	        		  role = resultSet.getString("role");
		    	        		  name = resultSet.getString("name");
		    	        		  username = resultSet.getString("author");
		    	        	  }	    	    
		    	        	  resultSet.close();
		        	          st.close();
		        	          con.close();
		    	          }
		    	          if(role!=null&&name!=null&&username!=null){
		    	        	  NodeInfo nodeInfo = new NodeInfo(username, role, name);
		    	        	  result = new IndexTreeNode(nodeInfo,language.getNum());    	        	 
		    	          }
		   	          
				  }catch(Exception err){
		    	          err.printStackTrace(System.out);
			      }
				  
				  return result;
			  }
			
		public static void copy(String str){
			StringSelection st = new StringSelection(str);
			Toolkit.getDefaultToolkit().getSystemClipboard().setContents(st, st);
		}
			

}


